﻿using machine_registration.Infrastructure;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using machine_registration.Helpers;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using System.ComponentModel.DataAnnotations;
using machine_registration.Models;
using Wpf.Ui;
using System.Windows.Navigation;
using machine_registration.Views;
using Microsoft.Extensions.DependencyInjection;
using System.Windows.Media;
using CommunityToolkit.Mvvm.Messaging;
using machine_registration.Views.Pages;
using System.ComponentModel.Design;
using Microsoft.Extensions.Logging;
namespace machine_registration.ViewModels
{
    public partial class DataQueryViewModel : ViewModel
    {

        private readonly AppDbContext _db;
        /// <summary>
        /// 数据源集合
        /// </summary>
        public ObservableCollection<DeviceInventory> DeviceInventory_ObservableCollection { get; } = new();
        /// <summary>
        /// 选择的项
        /// </summary>
        [ObservableProperty]
        public DeviceInventory _SelectedRecord;
        [ObservableProperty]
        private int _currentPage = 1;
        [ObservableProperty]
        private string _SearchKeyword;
        [ObservableProperty]
        public List<string> _SearchKeyword_list = new ();
     
        [ObservableProperty]
        private int _pageSize = 10;
        [ObservableProperty]
        private List<int> _pageSize_list = new() { 10,20,50,100};

        [ObservableProperty]
        public int _TotalCount;
        /// <summary>
        /// 设备类型选项
        /// </summary>
        public List<DeviceTypeOption> DeviceTypes { get; } = Enum.GetValues(typeof(DeviceType))
            .Cast<DeviceType>()
            .Select(t => new DeviceTypeOption(t))
            .ToList();

        /// <summary>
        /// 设备状态选项
        /// </summary>
        public List<DeviceInventoryStatus> DeviceStatus { get; } = Enum.GetValues(typeof(InventoryStatus))
            .Cast<InventoryStatus>()
            .Select(t => new DeviceInventoryStatus(t))
            .ToList();


        #region 搜索页面查询字段
        // 新增筛选属性
        [ObservableProperty]
        private DeviceType? _selectedDeviceType;

        [ObservableProperty]
        private InventoryStatus? _selectedStatus;

        [ObservableProperty]
        private bool _includeRetired;

        [ObservableProperty]
        private DateTime? _startDate;

        [ObservableProperty]
        private DateTime? _endDate;
        /// <summary>
        /// 对方信息  当前责任人
        /// </summary>
        [ObservableProperty]
        private string _CurrentKeeper = string.Empty;
        /// <summary>
        /// 对方信息  当前责任人列表
        /// </summary>
        [ObservableProperty]
        public List<string> _CurrentKeeper_list =new();
        /// <summary>
        /// 来源编号 
        /// </summary>
        [ObservableProperty]
        public string? _SourceNumber;

        /// <summary>
        /// 任务名称相关信息 
        /// </summary>
        [ObservableProperty]
        public string? _TaskName;

        
        #endregion

        [ObservableProperty]
        private bool _HasPreviousPage;

        [ObservableProperty]
        private bool _HasNextPage;
        // 修改分页属性计算
        public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
        // 命令系统 

        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        private INavigationService? navigationService;
        // 设备状态选项选项模型
        public class DeviceInventoryStatus
        {
            public InventoryStatus Value { get; }
            public string Description { get; }

            public DeviceInventoryStatus(InventoryStatus type)
            {
                Value = type;
                Description = type.GetDescription();
            }
        }
        private readonly ILogger<DataQueryViewModel> _logger;
        public DataQueryViewModel( AppDbContext dbContext, INavigationService _navigationService, ILogger<DataQueryViewModel> logger)
        {
            _logger = logger;
            _db = dbContext;
            navigationService = _navigationService;

            // 命令初始化 
            PreviousPageCommand = new RelayCommand(
                execute: () =>
                {
                    CurrentPage--;  // 页码递减
                                    // 注意：此处不需要手动调用 LoadPagedDataAsync，因为 CurrentPage 变更会自动触发
                },
                canExecute: () => HasPreviousPage  // 绑定到最新状态
            );

            NextPageCommand = new RelayCommand(
                execute: () =>
                {
                    CurrentPage++;  // 页码递增
                                    // 注意：此处不需要手动调用 LoadPagedDataAsync，因为 CurrentPage 变更会自动触发
                },
                canExecute: () => HasNextPage  // 绑定到最新状态
            );


        }
        /// <summary>
        /// 导航成功后调用
        /// </summary>
        public override void OnNavigatedTo()
        {
            //每次导航成功 都要刷新数据一次
            LoadPagedDataAsync().ConfigureAwait(false);
            // 加载责任人列表
            LoadCurrentKeepersAsync().ConfigureAwait(false);
            LoadDeviceNameAsync().ConfigureAwait(false);
        }

        [RelayCommand]
        private  void Particular()
        {
            if (SelectedRecord == null)
            {
                return;
            }
        }
        [RelayCommand]
        private async void Search()
        {
            _logger.LogDebug("搜索项目");
            CurrentPage = 1; // 重置到第一页
          await  LoadPagedDataAsync().ConfigureAwait(false);
            // 在UI线程检查结果
            if (TotalCount == 0)
            {
                await Application.Current.Dispatcher.Invoke(async () =>
                {
                    await ShowDialog("搜索提示", "没有找到符合条件的设备记录");
                });
            }
        }
        // 重置搜索条件命令
        [RelayCommand]
        private void ResetSearch()
        {
            SearchKeyword = string.Empty;
            SelectedDeviceType = null;
            SelectedStatus = null;
            IncludeRetired = false;
            StartDate = null;
            EndDate = null;
            SourceNumber = null;
            TaskName = null;
            CurrentKeeper = null;
       
            LoadPagedDataAsync().ConfigureAwait(false);
        }
        /// <summary>
        /// 借出设备按钮
        /// </summary>
        [RelayCommand]
        private async void lend()
        {
            if (SelectedRecord == null)
            {
                return;
            }
            if (SelectedRecord.IsRetired)
            {
               await ShowDialog("设备已报废", "设备已报废，无法借出");
                return;
            }
            _ = navigationService.Navigate(typeof(BorrowPage));
            // 发送消息，包含要传递的 ViewModel
            WeakReferenceMessenger.Default.Send(new PageNavigationMessage(SelectedRecord, "BorrowPageToken"), "BorrowPageToken");


        }



        private async Task ShowDialog(string title, string content)
        {
            var dialog = new Wpf.Ui.Controls.MessageBox
            {
                Title = title,
                Content = content,
                CloseButtonText = "我已知晓"
            };
            await dialog.ShowDialogAsync();
        }


        /// <summary>
        /// 加载当前责任人列表
        /// </summary>
        /// <returns></returns>
        private async Task LoadCurrentKeepersAsync()
        {
            try
            {
                var keepers = await _db.DeviceInventorys
                    .Where(d => !string.IsNullOrEmpty(d.CurrentKeeper))
                    .Select(d => d.CurrentKeeper)
                    .Distinct()
                    .OrderBy(k => k)
                    .ToListAsync();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    CurrentKeeper_list.Clear();
                    foreach (var keeper in keepers)
                    {
                        CurrentKeeper_list.Add(keeper);
                    }
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载责任人列表失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 加载设备名称列表绑定
        /// </summary>
        /// <returns></returns>
        private async Task LoadDeviceNameAsync()
        {
            try
            {
                var keepers = await _db.DeviceInventorys
                    .Where(d => !string.IsNullOrEmpty(d.DeviceName))
                    .Select(d => d.DeviceName)
                    .Distinct()
                    .OrderBy(k => k)
                    .ToListAsync();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    SearchKeyword_list.Clear();
                    foreach (var keeper in keepers)
                    {
                        SearchKeyword_list.Add(keeper);
                    }
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载设备名称列表失败: {ex.Message}");
            }
        }
        public async Task LoadPagedDataAsync()
        {
            try
            {

                var query = BuildQuery(); // 提取查询构建逻辑

                // 总数查询（必须使用相同的查询条件）
                TotalCount = await query.CountAsync();

                // 分页查询
                var data = await query
                    .Skip((CurrentPage - 1) * PageSize)
                    .Take(PageSize)
                    .ToListAsync();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    DeviceInventory_ObservableCollection.Clear();
                    foreach (var record in data)
                    {
                        DeviceInventory_ObservableCollection.Add(record);
                    }
                    UpdatePaginationState(); // 更新按钮状态
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"分页加载失败: {ex.Message}");
                // 实际项目中应添加错误处理逻辑 
            }
        }

        // 提取查询条件构建方法
        private IQueryable<DeviceInventory> BuildQuery()
        {
            var query = _db.DeviceInventorys
                .AsNoTracking()
                .OrderByDescending(r => r.EntryDate)
                .AsQueryable();

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(SearchKeyword))
            {
                query = query.Where(d =>
                    d.DeviceName.Contains(SearchKeyword) ||
                    d.MachineId.Contains(SearchKeyword) ||
                    d.SerialNumber.Contains(SearchKeyword));
            }

            if (SelectedDeviceType.HasValue)
            {
                query = query.Where(d => d.DeviceType == SelectedDeviceType.Value);
            }

            if (SelectedStatus.HasValue)
            {
                query = query.Where(d => d.Status == SelectedStatus.Value);
            }

            if (!IncludeRetired)
            {
                query = query.Where(d => !d.IsRetired);
            }

            if (StartDate.HasValue)
            {
                query = query.Where(d => d.EntryDate >= StartDate.Value);
            }

            if (EndDate.HasValue)
            {
                query = query.Where(d => d.EntryDate <= EndDate.Value.AddDays(1));
            }
            if (EndDate.HasValue)
            {
                query = query.Where(d => d.EntryDate <= EndDate.Value.AddDays(1));
            }
            // 添加当前责任人筛选
            if (!string.IsNullOrWhiteSpace(CurrentKeeper))
            {
                query = query.Where(d => d.CurrentKeeper == CurrentKeeper);
            }

            if (!string.IsNullOrWhiteSpace(SourceNumber))
            {
                query = query.Where(d => d.SourceNumber.Contains(SourceNumber));
            }
            if (!string.IsNullOrWhiteSpace(TaskName))
            {
                query = query.Where(d => d.TaskName.Contains(TaskName));
            }

            return query;
        }
        // 更新分页状态
        private void UpdatePaginationState()
        {
            HasPreviousPage = CurrentPage > 1;
            HasNextPage = CurrentPage < TotalPages;
   

            // 强制刷新命令状态
            (PreviousPageCommand as RelayCommand)?.NotifyCanExecuteChanged();
            (NextPageCommand as RelayCommand)?.NotifyCanExecuteChanged();
        }
        // 修改属性变更处理
        partial void OnPageSizeChanged(int value)
        {
            CurrentPage = 1;
            LoadPagedDataAsync().ConfigureAwait(false);
        }

        partial void OnCurrentPageChanged(int value)
        {
            LoadPagedDataAsync().ConfigureAwait(false);
        }


    }
    // 新增选项类
    public class StatusOption
    {
        public InventoryStatus Value { get; }
        public string Description { get; }

        public StatusOption(InventoryStatus status)
        {
            Value = status;
            Description = status.GetDescription();
        }
    }

}
